package com.cwolf.qr.activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.SurfaceHolder;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 预览 回调，具体频率没研究过
 */
class QrPreviewCallBack implements Camera.PreviewCallback {
    //解码状态监听
    QrScanerActivity qrScanerActivity;
    //线程池
    ExecutorService executor;
    //当前解码任务数
    int taskCount;
    //减少任务 0 不减少 ，1: 减少 1/3  2:减少 1/2， 3:全部不执行,打回5个以下
    int reduceState = 0;
    //取景框对应的图片的位置
    int[] picture_left_top_width_height = null;

    private Lock lock = new ReentrantLock();

    QrPreviewCallBack(QrScanerActivity listener) {
        this.qrScanerActivity = listener;
        executor = Executors.newFixedThreadPool(3);//解码图片用3个线程就可以了,没具体测试过

    }

    //二维码解码类
    MultiFormatReader multiFormatReader = new MultiFormatReader();

    @Override
    public void onPreviewFrame(final byte[] data, final Camera camera) {
//        Log.i("任务数量:", taskCount + "");

        executor.execute(new Runnable() {
            @Override
            public void run() {
                //是否执行解码任务
                boolean isDoTask = true;
                switch (reduceState) {
                    case 3:
                        isDoTask = false;
                        break;
                    case 2:
                        if (taskCount % 2 == 0) {
                            isDoTask = false;
                        }
                        break;
                    case 1:
                        if (taskCount % 3 == 0) {
                            isDoTask = false;
                        }
                        break;
                }


                try {
                    if (isDoTask&&qrScanerActivity.camera!=null) {

                        //获取当前待解析的任务数量
                        Camera.Size previewSize = camera.getParameters().getPreviewSize();//获取尺寸,格式转换的时候要用到
                        //获取二维码所在的位置
                        int width = previewSize.width;
                        int height = previewSize.height;

                        int[] picturePoint = getPicturePoint();

//                        Log.i("width-height--------->",width+""+height);//1280 720
                        PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data, width, height, picturePoint[1],
                                picturePoint[0], picturePoint[2], picturePoint[3], false);
                        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

                        final Result decode = multiFormatReader.decode(binaryBitmap);
                        bundleThumbnail(source);
                        Handler handler = new Handler(Looper.getMainLooper());
                         qrScanerActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                qrScanerActivity.decodeSuccess(decode);
                            }
                        });
                        executor.shutdownNow();//结束所有任务
                        executor = null;
                        taskCount = 0;

                    }
                } catch (NotFoundException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                taskReduce();

                //根据当前剩余任务数量，来计算需要减免的任务
                if (taskCount > 30) {
                    reduceState = 3;
                } else if (taskCount > 20) {
                    reduceState = reduceState > 2 ? reduceState : 2;
                } else if (taskCount > 5) {
                    reduceState = reduceState > 1 ? reduceState : 1;
                } else {
                    reduceState = 0;
                }

            }


        });

        taskPlus();
    }

    void taskPlus() {
        lock.lock();
        taskCount++;
        lock.unlock();

    }

    void taskReduce() {
        lock.lock();
        taskCount--;
        lock.unlock();
    }

    int[] getPicturePoint(){
        if(picture_left_top_width_height!=null){
            return picture_left_top_width_height;
        }
        Camera camera = qrScanerActivity.camera;
        Camera.Parameters parameters = camera.getParameters();
        //预览图大小
        Camera.Size previewSize = parameters.getPreviewSize();
        //图片是旋转了90度 的，长宽 相反
        int preview_height = previewSize.width;// 1280
        int preview_width = previewSize.height;// 720
        Rect finderViewRect = qrScanerActivity.getFinderViewRect();//长 700 宽 700
        double height_scale = (double) preview_height/qrScanerActivity.coverView.getHeight();//

        double width_scale = (double) preview_height/qrScanerActivity.coverView.getHeight();//0.5

        int imgWidth = (int) (finderViewRect.width()*width_scale);//
        int imgHeight = (int) (finderViewRect.height()*height_scale);//

        int left = (int) (preview_width-imgWidth)/2;// 左边不要解析的图片宽度
        int top =  (preview_height-imgHeight)/2;//上面不要解析的图片宽度


        //长宽多给一点点 20，这个可以不给
        picture_left_top_width_height = new int[]{
                left,top,imgWidth+20,imgHeight+20
        };
        return picture_left_top_width_height;
    }

    /**
     * 解码成功 预览取景框获取的图片
     * @param source
     */
    public  void bundleThumbnail(PlanarYUVLuminanceSource source) {
        int[] pixels = source.renderThumbnail();
        int width = source.getThumbnailWidth();
        int height = source.getThumbnailHeight();
        Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.ARGB_8888);
        SurfaceHolder holder = qrScanerActivity.coverView.getHolder();
        Rect finderViewRect = qrScanerActivity.getFinderViewRect();
        Canvas canvas = holder.lockCanvas(finderViewRect);
        Paint paint = new Paint();
        canvas.drawBitmap(bitmap,finderViewRect.left,finderViewRect.top,paint);
        holder.unlockCanvasAndPost(canvas);

    }
}
